<style lang="scss" src="./index.scss"></style>
<template>
    <div class="captcha-btn-box">
        <el-button
            class="captcha-btn__text"
            type="text"
            :disabled="_disabled || btnStatus === 1"
            @click="setCaptcha">
            {{btnText}}
        </el-button>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
@Component({
    name: "AuthCard"
})
export default class CaptchaBtn extends Vue {
    @Prop({
        type: String,
        default: ""
    }) readonly phone!: string;

    @Prop({
        type: Number,
        default: 60
    }) readonly count!: number;


    @Prop({
        type: Boolean,
        default: false
    }) readonly regCheck!: boolean;

    get _disabled() {
        return !this.phone;
    }

    btnText = "获取验证码";
    btnStatus = 0; // 0代表未发送 1代表已发送 2代表第一发送倒计时完成之后
    timer: any = null
    setCaptcha() {
        const info = {
            result: true,
            msg: ""
        };
        if (this._disabled) {
            info.result = false;
            info.msg = "请输入电话号码";
            this.$emit("on-send", info);
            return;
        }

        if (this.regCheck) {
            const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
            if (!reg.test(this.phone)) {
                info.result = false;
                info.msg = "请输入正确的电话号码";
                this.$emit("on-send", info);
                return;
            }
        }

        let count = this.count; // 验证码倒计时索引
        this.btnText = count + "s";
        this.btnStatus = 1;
        this.timer = setInterval(() => {
            count = count - 1;
            if (count <= 0) {
                this.btnText = "重新获取";
                this.btnStatus = 2;
                clearInterval(this.timer);
            } else {
                this.btnText = count + "s";
                this.btnStatus = 1;
            }
        }, 1000);
        this.$on('hook:beforeDestroy', () => {
            clearInterval(this.timer);
        });
        this.$emit("on-send", info);
    }

    clear() {
        this.btnText = "重新获取";
        this.btnStatus = 2;
        clearInterval(this.timer);
    }
}
</script>
